function isnull(str){if(str===null||str===""||str==="undefined"||undefined === str)return true;}
//img onerror=logo_other(this)
function logo_other(obj){
	try{
		//var obj = event.srcElement;
		obj.onerror=null;
		obj.src='./acl/common/upload/skins/small_logo.jpg';
		obj.title='未上传';
	}catch(ex){}
}

function initLayout(el) {
    var iContentW = $(window).width() - $("#sidebar").width() + 10 - 5;
    var iContentH = $(window).height() - $(".navbar-inverse").height() - 34;
    var colHeight=iContentH - $('.nav-tabs').height() - $('.footer').height() + 35;
    $('[role=main]').height(iContentH+30);
    $('.tab-content').height(colHeight);
    initTreeLayout(el);
}

function initTreeLayout(el) {
	try{
	    $("[layoutH]",el).layoutH();
	    $('.table-div').css({"border":"1px solid #dfdfe2"});
	    $('.tree-panel').css({
	    	"border-bottom":"1px solid #dfdfe2",
	    	"border-right":"1px solid #dfdfe2",
	    	"border-top":"1px solid #dfdfe2",
	   		"border-left":"0px solid #dfdfe2"
	    	});
	    $(el).initUI();
    }catch(e){}
 }
$.fn.extend({
    isTag:function(tn) {
        if(!tn) return false;
            return $(this)[0].tagName.toLowerCase() == tn?true:false;
    },
    layoutH: function($refBox){
        return this.each(function(){
            var $this = $(this);
            if (! $refBox) $refBox = $this.parents("div.layoutBox:first");
            var iRefH = $refBox.height();
            var iLayoutH = parseInt($this.attr("layoutH"));
            var iH = iRefH - iLayoutH > 50 ? iRefH - iLayoutH : 50;
            if ($this.isTag("table")) {
                $this.removeAttr("layoutH").wrap('<div layoutH="'+iLayoutH+'" style="overflow:auto;height:'+iH+'px"></div>');
            } else {
                $this.height(iH).css("overflow","auto");
            }
        });
    },
    initUI: function() {
        return this.each(function() {
            var $el=$(this || document);
            $(".btnTab a[value='"+$('.btnTab input',$el).val()+"']",$el).addClass('active');
            $('.form-validate',$el).validate({
                focusInvalid: true, 
                ignore: "",
                onkeyup: false,
                rules: {},
                errorPlacement: function (label, element) {
                  if($(element).hasClass("novalidate")){return;}
                  var $target = $(element).siblings('[for='+$(element).attr("id")+']:last');
        		  if($target.length==0){$target=$(element);}
                  $('<span class="help-inline"></span>').insertAfter($target.get(0)).append(label);
                  var parent = $(element).parents('.control-group');
                  parent.addClass('error');  
                },
                success: function (label, element) {
                  var parent = $(element).parents('.control-group');
                  parent.removeClass('error'); 
                }
            });
    	    $('.doc-form-validate',$el).validate({
        	    focusInvalid: true, 
        	    ignore: "",
        	    onkeyup: false,
        	    rules: {},
        	    errorPlacement: function (label, element) { 
        	      if($(element).hasClass("novalidate")){return;}
        	      if($(element).is(':hidden')){     	    	
        	    	  element = $(element).parent().get(0);
        	      }
        	      $(element).popover({
        	        content:label.html(),
        	        placement:'top',
        	        trigger:'manual',
        	        container:$(element).parent()
        	      }).popover('show');
        	    },
        	    success: function (label, element) {
        	    	if($(element).is(':hidden')){     	    	
          	    	    element = $(element).parent().get(0);
          	        }
        	        $(element).popover('destroy');
        	    }
        	}); 
        });
    }
})
_path = (function( script, i, me )
{
    var l = script.length;
    
    for( ; i < l; i++ )
    {
        me = !!document.querySelector ?
            script[i].src : script[i].getAttribute('src',4);

        if( me.substr(me.lastIndexOf('/')).indexOf('lhgdialog') !== -1 )
            break;
    }
    
    me = me.split('?'); _args = me[1];
    
    return me[0].substr( 0, me[0].lastIndexOf('/') + 1 );
})(document.getElementsByTagName('script'),0);

_webroot = (function( script, i, me )
{
    for (var i = 0; i < script.length; ++i) {
		var src = script.item(i).src;
		if (src) {
			var index = src.indexOf("jquery");
			if (index >= 0) {
				index = src.indexOf("cssui");
				return src.substring(0, index);
			}
		}
	}
	return;
})(document.getElementsByTagName('script'),0);

function blockUI(el, centerY) {
	el = el||$('.page-content');
    var el = jQuery(el);
    el.block({
        message: '<img src="'+_webroot+'cssui/images/ajax-loading.gif" align="">正在努力的加载,请稍等......',
        centerY: centerY != undefined ? centerY : true,
        css: {
            top: '10%',
            border: 'none',
            padding: '2px',
            backgroundColor: 'none'
        },
        overlayCSS: {
            backgroundColor: '#000',
            opacity: 0.05,
            cursor: 'wait'
        }
    });
}
function unblockUI(el) {
	el = el||$('.page-content');
    jQuery(el).unblock({
        onUnblock: function() {
            jQuery(el).removeAttr("style");
            initLayout(el);
        }
    });
}
/**
 * 渲染数据行
 * @param r 行号
 * @param theaderCells 表头模版
 * @param rowData  行数据,json格式
 * @return jQuery行对象
 */
function render_ajax_row(r,theaderCells,rowData){
	var tr = $('<tr></tr>');
	theaderCells.each(function(i){
		var fieldName = $(this).attr("field-name");
		var cellRender = $(this).attr("field-render");		
		var renderFunc = render_ajax_cell;
		if(cellRender){
			renderFunc = window[cellRender];			   
		} 
		var cellHtml='';
		if($.isFunction(renderFunc))
		{
			tr.append(renderFunc(i,fieldName,rowData));
		} 
		
	});
	return tr;
}
/**
 * @param r  行序号
 * @param c  列序号
 * @param field  字段名
 * @param rowData  行数据
 * @return td jQuery td对象
 */
function render_ajax_cell(r,c,fieldName,rowData){
	var td = $('<td></td>');
	var fieldValue = fieldName?rowData[fieldName]:'';
	 //字典数据以json方式显示 {code:'1',name:'男'}
	if(fieldValue && fieldValue.name)
		 fieldValue = fieldValue.name;	
	td.html(fieldValue?fieldValue:'');
	return td;
}

var handleSidebarMenu = function() {
    jQuery('.page-sidebar').on('mouseup', 'li > a', function(e) {
        if ($(this).next().hasClass('sub-menu') == false) {
            if ($('.btn-navbar').hasClass('collapsed') == false) {
                $('.btn-navbar').click();
            }
            return;
        }

        var parent = $(this).parent().parent();

        parent.children('li.open').children('a').children('.arrow').removeClass('open');
        parent.children('li.open').children('.sub-menu').slideUp(200);
        parent.children('li.open').removeClass('open');

        var sub = jQuery(this).next();
        if (sub.is(":visible")) {
            jQuery('.arrow', jQuery(this)).removeClass("open");
            jQuery(this).parent().removeClass("open");
            sub.slideUp(200, function() {
                //handleSidebarAndContentHeight();
            });
        } else {
            jQuery('.arrow', jQuery(this)).addClass("open");
            jQuery(this).parent().addClass("open");
            sub.slideDown(0, function() {
                //handleSidebarAndContentHeight();
            	//自适应scrollTop
            	var $target = jQuery(this).parent()
            		,height = 40
            		,count = $target.find('li').length
            		,needY = parseInt(height)*parseInt(count)
            		,realY = $('.page-sidebar').height()-$target.offset().top;
            	if(realY<needY){
            		var moveY = needY-realY;
            		//如果需要移动的长度长于目标的上头高度 
            		if(moveY>$target.offset().top){
            			moveY = $target.offset().top-height*2;
            		}
            		$('.page-sidebar').animate({scrollTop:($('.page-sidebar').scrollTop()+moveY)},200);
            	}
            });
        }

        e.preventDefault();
    });

    // handle ajax links
    jQuery('.page-sidebar').on('click', ' li > a.ajaxify', function(e) {
        e.preventDefault();
        App.scrollTop();

        var url = $(this).attr("href");
        var menuContainer = jQuery('.page-sidebar ul');
        var pageContent = $('.page-content');
        var pageContentBody = $('.page-content .page-content-body');

        menuContainer.children('li.active').removeClass('active');
        menuContainer.children('arrow.open').removeClass('open');

        $(this).parents('li').each(function() {
            $(this).addClass('active');
            $(this).children('a > span.arrow').addClass('open');
        });
        $(this).parents('li').addClass('active');

        App.blockUI(pageContent, false);

        $.post(url, {}, function(res) {
            App.unblockUI(pageContent);
            pageContentBody.html(res);
            App.fixContentHeight(); // fix content height
            App.initUniform(); // initialize uniform elements
        });
    });
}

var handleSidebarToggler = function() {
    // handle sidebar show/hide
    //$('.page-sidebar').on('click', '.sidebar-toggler', function(e) {
    $('.page-sidebar').on('click', '.folder', function(e) {
        var body = $('body');
        var sidebar = $('.page-sidebar');

        if ((body.hasClass("page-sidebar-hover-on") && body.hasClass('page-sidebar-fixed')) || sidebar.hasClass('page-sidebar-hovering')) {
            body.removeClass('page-sidebar-hover-on');
            sidebar.css('width', '').hide().show();
            e.stopPropagation();
//            runResponsiveHandlers();
            return;
        }

        $(".sidebar-search", sidebar).removeClass("open");

        if (body.hasClass("page-sidebar-closed")) {
            body.removeClass("page-sidebar-closed");
            if (body.hasClass('page-sidebar-fixed')) {
                sidebar.css('width', '');
            }
        } else {
            body.addClass("page-sidebar-closed");
        }

    });

    // handle the search bar close
    $('.page-sidebar').on('click', '.sidebar-search .remove', function(e) {
        e.preventDefault();
        $('.sidebar-search').removeClass("open");
    });

    // handle the search query submit on enter press
    $('.page-sidebar').on('keypress', '.sidebar-search input', function(e) {
        if (e.which == 13) {
            window.location.href = "extra_search.html";
            return false; //<---- Add this line
        }
    });
    // handle the search submit
    $('.sidebar-search .submit').on('click', function(e) {
        e.preventDefault();

        if ($('body').hasClass("page-sidebar-closed")) {
            if ($('.sidebar-search').hasClass('open') == false) {
                if ($('.page-sidebar-fixed').size() === 1) {
                    $('.page-sidebar .sidebar-toggler').click(); //trigger sidebar toggle button
                }
                $('.sidebar-search').addClass("open");
            } else {
                window.location.href = "extra_search.html";
            }
        } else {
            window.location.href = "extra_search.html";
        }
    });
}

$css={
    openDialog:function(params){
    	//{url:"",title:""}
    	//title
    	//$obj href="http://...." title="abc"
    	var url, title, rel, lock, data;
    	if(params instanceof jQuery) {
    		var $target = params,
    		url=$target.attr('href')?$target.attr('href'):'',
    		title=$target.attr('title')?$target.attr('title'):'',
    		rel = $target.attr('rel')?$target.attr('rel'):'',
    		lock = $target.attr('lock')?$target.attr('lock'):true,
    		data = '';
    	} else {
    		if (typeof(params) === 'string') {
					url=params,
					title='',
					rel='',
					lock=true,
					data='';
				}
				else{
				  url=params.url?params.url:'',
				  title=params.title?params.title:'',
				  rel=params.rel?params.rel:'',
				  lock=params.lock==null?true:params.lock,
				  data=params.data?params.data:'';
				}
    	}
        if(url.isExternalUrl()){
            $.dialog({
            	id:rel,
                title:title,				
                lock:true,
                width:500,
                height:300,
                content:'url:'+url
            });
        }else{
            var a={
            	id:rel,
                title:title,
                lock:lock,
                resize: false,
                max:false,
                min:false,
                padding: 0
            }
            var api = $.dialog(a);
            /* jQuery ajax */
            $.ajax({
                url:url,
								data: data,
							  type: 'POST',
					      success:function(content){
                    api.content(content);
                    //$(api.DOM.content[0]).initUI();
                    api.position('50%','38.2%');
                },
                cache:false
            });
        }
        return false;
    },
    focusDialog:function(){
        return $.dialog.focus.DOM.main[0];
    },
    closeDialog:function(){
        $.dialog.focus.close();
    },
    closeTab:function(){
    	$navTab.closeCurrentTab();
    },
    tip:function(content){
        $.dialog.tips(content,2,'success.gif');
    },
    alert:function(content,callback){
    	   $.dialog.alert('<div style="min-width:300px;">'+content+'</div>',callback);
    },
    confirm:function(content,callback1,callback2){
        $.dialog.confirm('<div style="min-width:300px;">'+content+'</div>', callback1, callback2);
    },
    login:function(){

    },
    timestampUrl:function(url){
    	if(url.indexOf('?')<0){
    		url += '?';
    	}else{
    		url += '&';
    	}
    	url += '_='+new Date().getTime();
    	return url;
    },
    post:function(url, data, callback, type){
        if ( jQuery.isFunction( data ) ) {
            callback = data;
            data = {};
        }
        return jQuery.ajax({
            type: "POST",
            url: $css.timestampUrl(url),
            data: data,
            success: function(data){
                if(jQuery.isFunction(callback))
                    callback(data);
            },
            dataType: type,
            error:function(e){
            	alert(e||'');
            }
        });
    },
    get:function(url, data, callback, type){
        if ( jQuery.isFunction( data ) ) {
            callback = data;
            data = null;
        }
        return jQuery.ajax({
            type: "GET",
            url: $css.timestampUrl(url),
            data: data,
            success: function(data){
                if(jQuery.isFunction(callback))
                    callback(data);
            },
            dataType: type,
            error:function(){

            }
        });
    },
    load:function(selector, url, data, callback, type){
        $.post(url,data,function(m){
            $(selector).html(m);
            callback();
        })
    },
    checkedVal:function(name, parent, split){
        var s=[];
        $('input[name="'+name+'"]:checked',$(parent)).each(function(i,t){
           s.push($(t).val());
        })
        return s.join(split);
    },
    parseUrl: function(b, a) {
        var c = b ? b: document.location.href;
        b = {};
        a = a || "?";
        if (!c.indexOf(a)) return b;
        a = c.split(a)[1].split("&");
        for (c = 0; c < a.length; c++) {
            var e = a[c].replace(/#.*$/g, "").split("=");
            e[1] || (e[1] = "");
            //b[e[0]] = UI.B.ie ? e[1] : UI.decode(e[1])
            b[e[0]] = e[1];
        }
        return b
    }
}
jQuery(document).ready(function() {
    $('body').off();
    $('body').on('click','[target=cssDialog]',function(){
	    return $css.openDialog($(this));
    });
    $('body').on('click','[target=closeTab]',function(){
    	return $navTab.closeCurrentTab();
    });
    $('body').on('click','[target=closeDialog]',function(){
    	return $css.closeDialog();
    });
 	handleSidebarMenu();
	handleSidebarToggler();
   
  var home={};
	home.id='home';
	home.title='首&nbsp;&nbsp;&nbsp;&nbsp;页';
	home.url='firstpage.jsp';
	$navTab.init('#tab-01',home);
	$navTab.event();
	$newTable.event();

	setTimeout(function(){
		initLayout();
	},0);
	$(window).resize(function(){
		initLayout();
	});
});

//兼容新版前台js
$.cssTab = {
	focus:function(){
	  return $navTab.focus();
	}
};
$.fn.cssTab = function(funcName,param){
	switch (funcName) {
		case 'reload':
			$navTab.reloadTab(param);
			break;
		default:
			break;
	}
};
//pushlet
var pushletMap = {};
function chat_init(tabid,topic){
	if(window.p_join_listen){
		pushletMap[tabid]=1;
		p_join_listen(topic);
	}
}


window.onData = function(event){
	var length  = Object.keys(pushletMap).length;
	var tabid = event.get('tabid');
	if(!tabid)return;
	delete pushletMap[tabid];
	//result 0:加载数据，1无数据忽略，2出错提示
	var result = event.get('result');
	if(result==='0'){
		//$action.ajaxSubmit('dirFwPushletMini.action','token='+$('#token',$navTab.focus()).val(),$('form table tbody',$navTab.focus()));
		$('form table tbody',$('.tab-content .tab-pane#'+tabid)).html(event.get('info'));
	}else if(result==='2'){
		alert(event.get('info')||'');
	}
	length  = Object.keys(pushletMap).length;
	if(length==0)p_leave();
	
}

function research(){
	$('[name="page.currentPage"]',$navTab.focus()).val(1);
	$('form',$navTab.focus()).submit();
}